#include "database_manager.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QDir>
#include <QStandardPaths>

DatabaseManager& DatabaseManager::instance() {
    static DatabaseManager instance;
    return instance;
}

DatabaseManager::~DatabaseManager() {
    if (m_database.isOpen()) {
        m_database.close();
    }
}

bool DatabaseManager::initializeDatabase() {
    // 设置数据库路径
    QString dataPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QDir dir(dataPath);
    if (!dir.exists()) {
        dir.mkpath(".");
    }
    
    QString dbPath = dataPath + "/inventory.db";
    
    m_database = QSqlDatabase::addDatabase("QSQLITE");
    m_database.setDatabaseName(dbPath);
    
    if (!m_database.open()) {
        QMessageBox::critical(nullptr, "错误", 
                            "无法打开数据库: " + m_database.lastError().text());
        return false;
    }
    
    // 检查是否需要创建表
    QStringList tables = m_database.tables();
    if (tables.isEmpty()) {
        return createTables() && insertDefaultData();
    }
    
    return true;
}

bool DatabaseManager::createTables() {
    QSqlQuery query;
    
    // 创建用户表
    if (!query.exec("CREATE TABLE users ("
                   "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                   "username VARCHAR(50) UNIQUE NOT NULL,"
                   "password VARCHAR(100) NOT NULL,"
                   "role VARCHAR(20) DEFAULT 'user',"
                   "created_time DATETIME DEFAULT CURRENT_TIMESTAMP)")) {
        QMessageBox::critical(nullptr, "错误", "创建用户表失败: " + query.lastError().text());
        return false;
    }
    
    // 创建产品表
    if (!query.exec("CREATE TABLE products ("
                   "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                   "name VARCHAR(100) NOT NULL,"
                   "barcode VARCHAR(50) UNIQUE NOT NULL,"
                   "price DECIMAL(10,2) NOT NULL,"
                   "cost DECIMAL(10,2) NOT NULL,"
                   "stock_quantity INTEGER DEFAULT 0,"
                   "min_stock INTEGER DEFAULT 10,"
                   "category VARCHAR(50),"
                   "supplier VARCHAR(100),"
                   "description TEXT,"
                   "created_time DATETIME DEFAULT CURRENT_TIMESTAMP,"
                   "updated_time DATETIME DEFAULT CURRENT_TIMESTAMP)")) {
        QMessageBox::critical(nullptr, "错误", "创建产品表失败: " + query.lastError().text());
        return false;
    }
    
    // 创建入库记录表
    if (!query.exec("CREATE TABLE stock_in ("
                   "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                   "product_id INTEGER NOT NULL,"
                   "quantity INTEGER NOT NULL,"
                   "unit_price DECIMAL(10,2) NOT NULL,"
                   "total_amount DECIMAL(10,2) NOT NULL,"
                   "supplier VARCHAR(100),"
                   "operator_id INTEGER NOT NULL,"
                   "operation_time DATETIME DEFAULT CURRENT_TIMESTAMP,"
                   "FOREIGN KEY (product_id) REFERENCES products(id),"
                   "FOREIGN KEY (operator_id) REFERENCES users(id))")) {
        QMessageBox::critical(nullptr, "错误", "创建入库记录表失败: " + query.lastError().text());
        return false;
    }
    
    // 创建销售记录表
    if (!query.exec("CREATE TABLE sales ("
                   "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                   "product_id INTEGER NOT NULL,"
                   "quantity INTEGER NOT NULL,"
                   "unit_price DECIMAL(10,2) NOT NULL,"
                   "total_amount DECIMAL(10,2) NOT NULL,"
                   "customer_info TEXT,"
                   "operator_id INTEGER NOT NULL,"
                   "operation_time DATETIME DEFAULT CURRENT_TIMESTAMP,"
                   "FOREIGN KEY (product_id) REFERENCES products(id),"
                   "FOREIGN KEY (operator_id) REFERENCES users(id))")) {
        QMessageBox::critical(nullptr, "错误", "创建销售记录表失败: " + query.lastError().text());
        return false;
    }
    
    return true;
}

bool DatabaseManager::insertDefaultData() {
    QSqlQuery query;
    
    // 插入默认管理员账户
    if (!query.exec("INSERT INTO users (username, password, role) VALUES ('admin', 'admin123', 'admin')")) {
        QMessageBox::critical(nullptr, "错误", "插入默认用户失败: " + query.lastError().text());
        return false;
    }
    
    // 插入一些示例产品数据
    if (!query.exec("INSERT INTO products (name, barcode, price, cost, stock_quantity, category, supplier) "
                   "VALUES "
                   "('笔记本电脑', '6921234567890', 5999.00, 4500.00, 50, '电子产品', '联想集团'),"
                   "('无线鼠标', '6921234567891', 89.00, 45.00, 200, '电子产品', '罗技公司'),"
                   "('机械键盘', '6921234567892', 399.00, 250.00, 100, '电子产品', '樱桃公司'),"
                   "('显示器', '6921234567893', 1299.00, 900.00, 30, '电子产品', '戴尔公司')")) {
        QMessageBox::warning(nullptr, "警告", "插入示例产品数据失败: " + query.lastError().text());
    }
    
    return true;
}

QSqlDatabase DatabaseManager::database() const {
    return m_database;
}